import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shenling_logistics/components/FuncComp.dart';
import 'package:shenling_logistics/utils/Auth.dart';
import 'package:shenling_logistics/utils/EventBus.dart';
import 'package:shenling_logistics/utils/Http.dart';
import 'package:shenling_logistics/utils/Toast.dart';

class MineIndex extends StatefulWidget {
  const MineIndex({super.key});

  @override
  State<MineIndex> createState() => _MineIndexState();
}

class _MineIndexState extends State<MineIndex> {
  List tasks = [
    {'label': "任务总量", 'count': 18},
    {'label': "完成任务量", 'count': 16},
    {'label': "运输里程(km)", 'count': 3987},
  ];

  // 司机用户信息
  Map driverInfo = {};

  @override
  void initState() {
    super.initState();
    // 获取司机用户信息
    eventBus.on<UserDataInEvent>().listen((event) {
      getUserInfo();
      getTask();
    });
  }

  // 获取司机任务信息
  Future<void> getTask() async {
    if (!Auth().checkAuth()) return;

    // 获取当前年月
    final now = DateTime.now();
    final currentMonth = now.month.toString().padLeft(2, '0'); // 确保月份是两位数
    final currentYear = now.year.toString();
    try {
      final res = await http.get('/driver/users/taskReport',
          params: {'month': currentMonth, 'year': currentYear});
      setState(() {
        // 任务总量
        tasks[0]['count'] = res['data']['taskAmounts'];
        // 任务完成量
        tasks[1]['count'] = res['data']['completedAmounts'];
        // 运输公里数
        tasks[2]['count'] = res['data']['transportMileage'];
      });
    } catch (e) {
      CustomToast.error('网络异常$e');
    }
  }

  // 获取司机用户信息
  void getUserInfo() async {
    if (Auth().checkAuth()) return;

    try {
      final res = await http.get('/driver/users');
      setState(() {
        driverInfo = res['data'];
      });
    } catch (e) {
      CustomToast.error('网络异常');
    }
  }

  // 手机号格式化
  String formatPhoneNumber(String phoneNumber) {
    if (phoneNumber.length != 11) {
      return phoneNumber; // 如果不是11位数字，直接返回原字符串
    }
    return '${phoneNumber.substring(0, 3)} ${phoneNumber.substring(3, 7)} ${phoneNumber.substring(7)}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            color: Colors.grey[200],
            height: MediaQuery.of(context).size.height,
            child: Stack(
              alignment: Alignment.topCenter,
              children: [
                Image.asset(
                  'assets/bg_page_my.png',
                  width: MediaQuery.of(context).size.width,
                  fit: BoxFit.cover,
                  repeat: ImageRepeat.repeat,
                ),
                Container(
                  margin: EdgeInsets.only(top: 50),
                  child: Column(
                    children: [
                      // 头像
                      driverInfo['avatar'] == null
                          ? SvgPicture.asset('assets/ic_avatar_driver.svg')
                          : Image.network(
                              driverInfo['avatar'],
                              width: 68,
                              height: 68,
                            ),

                      SizedBox(
                        height: 8.5,
                      ),

                      //  用户昵称
                      Text(
                        '${driverInfo['name'] ?? '默认用户'}',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.w500),
                      ),

                      SizedBox(
                        height: 8.5,
                      ),

                      // 司机编号
                      Text(
                        '司机编号：${driverInfo['number'] ?? "67409881"}',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w400),
                      ),

                      SizedBox(
                        height: 5,
                      ),

                      // 手机号
                      Text(
                        '手机号：${formatPhoneNumber(driverInfo["phone"] ?? "17799988765")}',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w400),
                      ),

                      SizedBox(
                        height: 26.5,
                      ),

                      // 本月任务
                      Container(
                        width: 345,
                        height: 135,
                        padding: EdgeInsets.only(top: 15, bottom: 15),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Column(
                          children: [
                            Text(
                              '- 本月任务 -',
                              style: TextStyle(
                                  fontSize: 14, color: Colors.grey[400]),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 20),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: tasks.map((e) {
                                  return Column(
                                    children: [
                                      Text(
                                        '${e["count"]}',
                                        style: TextStyle(
                                            fontWeight: FontWeight.w600,
                                            fontSize: 18),
                                      ),
                                      Text(
                                        '${e["label"]}',
                                        style: TextStyle(fontSize: 12),
                                      )
                                    ],
                                  );
                                }).toList(),
                              ),
                            )
                          ],
                        ),
                      ),

                      Container(
                        margin: EdgeInsets.only(top: 15),
                        padding: EdgeInsets.only(left: 17.5, right: 12.5),
                        width: 345,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8)),
                        child: Column(
                          children: [
                            FuncComp(
                              label: '车辆信息',
                            ),
                            FuncComp(label: '任务数据'),
                            FuncComp(
                              label: '系统设置',
                              onCallback: () {
                                //  跳转系统设置
                                Navigator.pushNamed(context, '/setting');
                              },
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ],
            )));
  }
}
